package cn.lyjuan.android.mylibrary.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * 授权工具，仅API 23及以上需要
 * Created by chad on 14/11/2017.
 */
public class PermissionUtils
{
    /**
     * 授权
     *
     * @param enforces 强制需要的权限，每次都会提示
     * @param recom    建议需要的权限，非必须
     *                 @return true表示拥有所有权限;false表示需要等待用户授权
     */
    @TargetApi(Build.VERSION_CODES.M)
    public static boolean grant(Activity context, List<String> enforces, @Nullable List<String> recom)
    {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
            return true;

        List<String> ps = new ArrayList<>();

        if (null != enforces && !enforces.isEmpty())
        {
            for (String e : enforces)
            {
                if (context.checkSelfPermission(e) != PackageManager.PERMISSION_GRANTED)
                    ps.add(e);
            }
        }

        if (null != recom && !recom.isEmpty())
        {
            for (String r : recom)
            {
                if (context.shouldShowRequestPermissionRationale(r))
                    ps.add(r);
            }
        }

        if (!ps.isEmpty())
            context.requestPermissions(ps.toArray(new String[ps.size()]), 127);

        return ps.isEmpty();
    }
}
